import { mapGetters, mapMutations } from 'vuex';
import { playMode } from '@/common/js/config';
import { saveLoveSong, removeLoveSong } from '@/common/js/cache';

export const playlistMixin = {
  computed: {
    ...mapGetters(['playlist']),
  },
  mounted() {
    this.handlePlayList(this.playlist);
  },
  // 对应到keep-alive
  activated() {
    this.handlePlayList(this.playlist);
  },
  methods: {
    handlePlayList() {
      // 覆盖的特性,保证在局部的组件里存在这个【独特】方法
      throw new Error('add the handle in compnents plz...');
    },
  },
  watch: {
    playlist(now) {
      this.handlePlayList(now);
    },
  },
};

export const playerMixin = {
    computed: {
        modeInfo() {
        const obj = {};
        if (this.mode === playMode.sequence) {
            obj.icon = 'icon-sequence';
            obj.text = '顺序播放';
        }
        if (this.mode === playMode.loop) {
            obj.icon = 'icon-loop';
            obj.text = '单曲循环';
        }
        if (this.mode === playMode.random) {
            obj.icon = 'icon-random';
            obj.text = '随机播放';
        }
        return obj;
    },
        ...mapGetters(['mode', 'currentSong', 'loveList']),
    },
    methods: {
        changeMode() {
            let mode = this.mode + 1;
            mode %= 3;
            this.SET_PLAY_MODE(mode);
        },
        toggleLove(song) {
            if (!this.isLove(song)) {
                this.SET_LOVE_LIST(saveLoveSong(song));
            } else {
                this.SET_LOVE_LIST(removeLoveSong(song));
            }
        },
        isLove(song) {
            const index = this.loveList.findIndex(item => item.id === song.id);
            return index !== -1;
        },
        ...mapMutations([
            'SET_PLAY_MODE',
            'SET_LOVE_LIST',
        ]),
    },
};

export const searchMixin = {
    computed: {
        ...mapGetters(['playHistory', 'searchHistory']),
    },
    methods: {
        blur() {
            this.$refs.searchBox.blur();
        },
        setKeyword(text) {
            if (typeof text === 'string') {
                this.keyword = text;
            } else {
                this.keyword = text.name;
            }
        },
        ...mapMutations(['SET_SEARCH_HISTORY']),
    },
};
